import { observer } from 'mobx-react'
import { useEffect, useRef, useState } from 'react'
import {
  Button,
  Card,
  Form,
  Input,
  Select,
  Space,
  Table,
  DatePicker,
  message,
  Badge,
  Avatar,
  Radio
} from 'antd'
import { ReloadOutlined, SearchOutlined, UserOutlined } from '@ant-design/icons'
import { ColumnsType } from 'antd/es/table'
import { getTerminalManagementList } from '@/apis/terminalManagement/terminalManagement'
const { Option } = Select
const { RangePicker } = DatePicker

interface DataType {
  id: string
  key: string
  serialNumber: number
  productName: string
  platform: string
  version: string
  status: string
  updateDescription: string
  downloadUrl: string
  operator: string
  operationTime: string
}
// 定义筛选表单的接口
interface FilterForm {
  startTime: string
  endTime: string
  operationUser: string
  dateRange: [string, string] | null
}

const TerminalManagement: React.FC = () => {
  // 初始化表单状态
  const initialFilterForm: FilterForm = {
    startTime: '',
    endTime: '',
    operationUser: '',
    dateRange: ['', '']
  }

  const [data, setData] = useState<DataType[]>([])
  const [loading, setLoading] = useState(false)

  const [searchForm, setSearchForm] = useState<FilterForm>(initialFilterForm)

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })

  const getData = async (params = {}) => {
    try {
      setLoading(true)
      const response = await getTerminalManagementList({
        ...searchForm,
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      })
      if (response.code === 200) {
        // 为每条数据添加唯一的 key
        const listWithKeys = response.data.list.map((item: any) => ({
          ...item,
          key: item.id
        }))
        setData(listWithKeys)
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }))
      } else {
        message.error(response.message || '获取数据失败')
      }
    } catch (error) {
      console.log(error)
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }
  // 搜索事件处理
  const handleSearch = async () => {
    try {
      const { dateRange, ...rest } = searchForm
      const params = {
        ...rest,
        current: 1,
        pageSize: pagination.pageSize,
        startTime: dateRange?.[0] || undefined,
        endTime: dateRange?.[1] || undefined
      }

      setPagination(prev => ({ ...prev, current: 1 }))
      await getData(params)
    } catch (error) {
      console.error('查询失败:', error)
      message.error('查询失败')
    }
  }
  /**
   * 重置表单
   */
  const resetSearchForm = () => {
    setSearchForm(initialFilterForm)
    setPagination(prev => ({ ...prev, current: 1 }))
    getData({
      ...initialFilterForm,
      current: 1,
      pageSize: pagination.pageSize
    })
  }
  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize
    }))
    getData({
      current: newPagination.current,
      pageSize: newPagination.pageSize
    })
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      render: (text: any, record: any, index: number) => {
        // 计算序号，分页时会自动显示正确的序号
        return index + 1
      }
    },
    {
      title: '终端ID',
      dataIndex: 'terminalId',
      key: 'terminalId'
    },
    {
      title: '终端名称',
      dataIndex: 'terminalName',
      key: 'terminalName'
    },
    {
      title: '终端状态',
      dataIndex: 'terminalStatus',
      key: 'terminalStatus',
      render: (status: number) => (
        <>
          <Badge
            status={['error', 'success'][status] as any}
            styles={{ indicator: { marginRight: '8px' } }}
          />
          {['离线', '在线'][status]}
        </>
      )
    },
    {
      title: '终端类型 ',
      dataIndex: 'terminalType',
      key: 'terminalType'
    },
    {
      title: '绑定用户',
      dataIndex: 'boundUser',
      key: 'boundUser',
      render: boundUser => (
        <div style={{ display: 'flex', alignItems: 'center', gap: '5px' }}>
          <Avatar icon={<UserOutlined />} />
          <div className="user-info" style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
            <span style={{ color: '#02A7F0' }}>账号：{boundUser.username}</span>
            <span>ID：{boundUser.id}</span>
          </div>
        </div>
      )
    },
    {
      title: '最近登陆时间',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime'
    },
    {
      title: '操作人',
      dataIndex: 'operator',
      key: 'operator'
    },
    {
      title: '操作时间',
      dataIndex: 'operationTime',
      key: 'operationTime'
    },
    {
      title: '操作',
      key: 'ip',
      render: (item, e) => (
        <Space className='table-cell-actions'>
          <Button type="link">详情</Button>
          <Button type="link">编辑</Button>
        </Space>
      )
    }
  ]

  // 页面初始化时获取数据
  useEffect(() => {
    getData()
  }, [])
  const [filter, setFilter] = useState(0)
  return (
    <div className="app-container">
      <Space size={12} className="tab-btn">
        {['终端列表', '终端黑名单', '安全策略'].map((e, index) => (
          <Button
            key={index}
            shape="round"
            type={filter === index ? 'link' : 'text'}
            style={{ background: filter === index ? '#F2F3F5' : '' }}
            onClick={() => setFilter(index)}
          >
            {e}
          </Button>
        ))}
      </Space>
      {filter === 0 && (
        <>
          <div className="filterForm" style={{paddingTop: '45px'}}>
            <Form
              variant={'filled'}
              layout="inline"
              className="form"
              colon={false}
            >
              <Form.Item name="终端" label="终端">
                <Input
                  placeholder="请输入终端ID"
                  addonBefore={
                    <Select value={''} placeholder="">
                      <Option value="">终端ID</Option>
                      <Option value="female">female</Option>
                      <Option value="other">other</Option>
                    </Select>
                  }
                />
              </Form.Item>
              <Form.Item name="用户" label="用户">
                <Input
                  placeholder="请输入用户登录帐号"
                  addonBefore={
                    <Select value={''} placeholder="">
                      <Option value="">账号</Option>
                      <Option value="female">female</Option>
                      <Option value="other">other</Option>
                    </Select>
                  }
                />
              </Form.Item>
              <Form.Item name="筛选方式" label="筛选方式">
                <Select placeholder="请选择筛选方式" allowClear>
                  <Option value="">male</Option>
                  <Option value="female">female</Option>
                  <Option value="other">other</Option>
                </Select>
              </Form.Item>
              <Form.Item name="操作人" label="操作">
                <Input placeholder="请输入操作人账号" />
              </Form.Item>
              <Form.Item name="操作时间" label="操作时间">
                <RangePicker />
              </Form.Item>
            </Form>
            <div className="rightAction">
              <Button type="primary" htmlType="submit" onClick={handleSearch}>
                <SearchOutlined />
                查询
              </Button>
              <Button onClick={resetSearchForm}>
                <ReloadOutlined />
                重置
              </Button>
            </div>
          </div>
          <Table
              columns={columns}
              dataSource={data}
              pagination={{
                ...pagination,
                showSizeChanger: true,
                showTotal: total => `共 ${total} 条`
              }}
              onChange={handleTableChange}
              loading={loading}
            />
        </>
      )}
    </div>
  )
}

export default observer(TerminalManagement)
